//引用所需要的模块
const obj = require('../db');
// 调用 postgres 数据表 User、Messages、Comment
let { User,Message,Comment, sync } = require('../models');
// 调用用户认证--auth模块
const auth = require('../utils/auth');

// 显示加载首页界面
let index_fn = async (ctx, next) => {
    // 加载显示当前用户
    let username = ctx.session.userName;
    let obj={
        username:username
    }
    ctx.render("index.html",obj)
}
let personal_fn = async (ctx, next) => {
    // 加载显示当前用户
    // let username = ctx.session.userName;
    // let obj={
    //     username:username
    // }
    ctx.render("personal.html")
}
//显示加载产品案例界面
let work_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let obj={
        username:username
    }
    ctx.render("work.html",obj)
}
//显示加载新闻中心界面
let blog_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let obj={
        username:username
    }
    ctx.render("blog.html",obj)
}
//显示加载关于我们界面
let about_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let obj={
        username:username
    } 
    ctx.render("about.html",obj)
}
//显示加载联系我们界面
let contact_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let obj={
        username:username
    } 
    ctx.render("contact.html",obj)
}

let work_single_fn = async(ctx,next)=>{
    ctx.render("work-single.html")
}
// 显示加载登录界面 /login在Sign_up下
let login_fn = async (ctx, next) => {
    ctx.render("./Sign_up/login.html")
}
// 显示加载注册界面 /register在Sign_up下
let register_fn = async (ctx, next) => {
    ctx.render("./Sign_up/register.html")
}

// 加载处理登录请求
let loginDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = { code: 200, msg: '登录成功' };
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请确认后重试' };
        }

    } else {
        res = { code: 1000, msg: '用户名和密码不能为空' };
    }
    ctx.body = JSON.stringify(res);
};

// 加载处理注册请求
let registerDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';
    let confirmpwd = ctx.request.body.confirmpassword.trim() || '';

    let res = '';

    // 判断用户名、密码是否为空，为空则返回提示信息；不为空则尝试从数据库中查询是否有同名用户，如果没有，则创建用户；如果有，则返回提示信息；
    // 初步尝试then的玩法，出现了一些顺序问题（前端获取的返回数据为空的情况）
    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await User.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json === 'null') {
            let u1 = await User.create({
                username: uid,
                password: pwd
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200, msg: '用户注册成功' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且两密码应该一致' };
        console.log(uid);
        console.log(pwd);
        console.log(confirmpwd);
    }
    // 返回消息
    ctx.body = JSON.stringify(res);
};

// 注销加载
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}

module.exports = {
    "/": ["get", auth, index_fn],             //加载首页
    "/personal": ["get", personal_fn],        //个人中心
    "/work": ['get', work_fn],                //加载产品案例
    "/about": ['get', about_fn],              //加载关于我们     
    "/contact": ['get', contact_fn],          //加载联系我们
    "/blog": ['get', blog_fn],                //加载新闻中心
    "/work-single": ['get', work_single_fn],        //加载新闻中心
    

    '/logout': ['post', auth, logout_fn],           //注销
    '/login': ['get',auth, login_fn],               //加载登录界面
    '/register': ['get', register_fn],              //加载注册界面
    '/loginDone': ['post', loginDone_fn],           // 加载处理登录请求
    '/registerDone': ['post', registerDone_fn],     // 加载处理注册请求
}
